<template>
    <div class="login-container">
        <a-card title="登录" :style="{ width: '400px' }">
            <a-form :model="formState" @finish="onFinish">
                <a-form-item label="用户名" name="username" :rules="[{ required: true, message: '请输入用户名' }]">
                    <a-input v-model:value="formState.username" />
                </a-form-item>
                <a-form-item label="密码" name="password" :rules="[{ required: true, message: '请输入密码' }]">
                    <a-input-password v-model:value="formState.password" />
                </a-form-item>
                <a-form-item>
                    <a-button type="primary" html-type="submit" :loading="loading">登录</a-button>
                </a-form-item>
            </a-form>
        </a-card>
    </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useStore } from 'vuex';
import { message } from 'ant-design-vue';
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';

interface FormState {
    username: string;
    password: string;
}

export default defineComponent({
    name: 'Login',
    setup() {
        const router = useRouter();
        const route = useRoute();
        const store = useStore();
        const loading = ref(false);

        const formState = reactive<FormState>({
            username: '',
            password: ''
        });

        const onFinish = async (values: FormState) => {
            loading.value = true;
            try {
                // 1. 首先检查是否在主应用中运行，且主应用是否已登录
                if (qiankunWindow.__POWERED_BY_QIANKUN__) {
                    // @ts-ignore
                    const { getGlobalState } = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
                    const state = getGlobalState();
                    if (state.isLogin) {
                        // 使用主应用的登录状态
                        store.commit('setToken', state.token);
                        store.commit('setUserInfo', state.userInfo);
                        store.commit('setIsLogin', true);
                        
                        // 跳转到之前要访问的页面或首页
                        const redirect = route.query.redirect as string;
                        router.push(redirect || '/');
                        return;
                    }
                }

                // 2. 如果主应用未登录或独立运行，执行自己的登录逻辑
                // 这里模拟登录请求
                await new Promise(resolve => setTimeout(resolve, 1000));
                
                if (values.username === 'admin' && values.password === 'admin') {
                    // 登录成功
                    const loginData = {
                        token: 'app1-token-' + Date.now(),
                        userInfo: {
                            username: values.username,
                            roles: ['admin']
                        }
                    };

                    // 更新本地状态
                    store.commit('setToken', loginData.token);
                    store.commit('setUserInfo', loginData.userInfo);
                    store.commit('setIsLogin', true);

                    // 如果在qiankun环境中，同步状态到主应用
                    if (qiankunWindow.__POWERED_BY_QIANKUN__) {
                        // @ts-ignore
                        const { setGlobalState } = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
                        setGlobalState({
                            token: loginData.token,
                            userInfo: loginData.userInfo,
                            isLogin: true
                        });
                    }

                    message.success('登录成功');
                    
                    // 跳转到之前要访问的页面或首页
                    const redirect = route.query.redirect as string;
                    router.push(redirect || '/');
                } else {
                    message.error('用户名或密码错误');
                }
            } catch (error) {
                console.error('登录失败:', error);
                message.error('登录失败，请重试');
            } finally {
                loading.value = false;
            }
        };

      

        return {
            formState,
            loading,
            onFinish,
            toHome
        };
    }
});
</script>

<style lang="less" scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f2f5;
}
</style> 